package com.tang.reggie.controller;

import com.tang.reggie.common.R;
import com.tang.reggie.pojo.User;
import com.tang.reggie.service.UserService;
import com.tang.reggie.utils.SMSUtils;
import com.tang.reggie.utils.SMSUtils2;
import com.tang.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMag(@RequestBody User user, HttpSession session){
        log.info("前台用户模块:发送验证码功能");
        String phone=user.getPhone();
        if (StringUtils.isNotBlank(phone)){
            String code = ValidateCodeUtils.generateValidateCode4String(6);
            log.info("验证码：{}",code);
            //SMSUtils.sendMessage(phone,code);
            //SMSUtils2.sendMessage(phone,code);
            //发送成功后就将验证码存入session中
            session.setAttribute(phone,code);

            //验证码存入到redis中，并设置过期时间5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.success("发送成功");
        }
        return R.error("手机号为空，请输入后发送");
    }

    /**
     * 登录校验
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody User user,HttpSession session){
        log.info("前台用户模块:登录功能");
        String phone = user.getPhone();
        String code = user.getCode();

        //校验的验证码
//        Object code1 = session.getAttribute(phone);
        //从Redis中去验证码
        Object code1=redisTemplate.opsForValue().get(phone);
        if (code1!=null&&code1.equals(code)){
            User user1=userService.login(phone);
            session.setAttribute("user",user1.getId());
            //登录成功后去除验证码
            redisTemplate.delete(phone);
            return R.success(user1);
        }
        return R.error("验证码错误，请重新登录");
    }

    /**
     * 前台用户退出
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R loginout(HttpSession session){
        log.info("前台用户模块:注销功能");
        session.invalidate();
        return R.success("退出成功");
    }

}
